/*
 * @lc app=leetcode.cn id=968 lang=cpp
 *
 * [968] 监控二叉树
 */
#include "include.h"

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int minCameraCover(TreeNode* root) {
        if (postOrderTraverse(root) == request_one) {
            monitorCounter_ += 1;
        }
        return monitorCounter_;
    }
private:
    int monitorCounter_ = 0;
    enum status {
        // have_no_son = -1,
        request_one = 0,
        have_one = 1,
        borrow_one = 2
    };
private:
    int postOrderTraverse(TreeNode* root) {
// printf("check %p %p %p\n", root, root->left, root->right);
        // have no son <=> two son borrow from lower layer
        int leftStatus = borrow_one;
        int rightStatus = borrow_one;

        if (root->left) {leftStatus = postOrderTraverse(root->left);}
        if (root->right) {rightStatus = postOrderTraverse(root->right);}
        
        // left or right need one, have to apply for a new one
        if (leftStatus == request_one or rightStatus == request_one) {
            monitorCounter_ += 1;
// printf("%p have one\n", root);
            return have_one;
        }

        // and then check left and right both need to borrow from lower layer
        // or have no left / right son
        if ((leftStatus == borrow_one and rightStatus == borrow_one)) {
// printf("%p request one\n", root);
            return request_one;
        }

        // now it must be :
        // one borrow, one have
        // root can borrow from one of his son, no need to request
// printf("%p borrow one\n", root);
        return borrow_one;
    }
};
// @lc code=end
